package com.ruoyi.deviceManagement.service;
import com.ctg.ag.sdk.biz.AepDeviceManagementClient;
import com.ctg.ag.sdk.biz.aep_device_management.CreateDeviceRequest;
import com.ctg.ag.sdk.biz.aep_device_management.CreateDeviceResponse;
import com.ctg.ag.sdk.biz.aep_device_management.DeleteDeviceRequest;
import com.ctg.ag.sdk.biz.aep_device_management.DeleteDeviceResponse;
import com.ctg.ag.sdk.biz.aep_device_management.UpdateDeviceRequest;
import com.ctg.ag.sdk.biz.aep_device_management.UpdateDeviceResponse;

import org.json.JSONObject;

/**
 * 设备CRUD服务类，实现设备的创建、查询、更新和删除功能，并将数据存储在SQL Server中
 */

import java.nio.charset.StandardCharsets;


public class DeviceCrudService {

    private AepDeviceManagementClient client;
    private String masterKey="41975c421b07461caa6f585ea0f0c765";
    private Long productId=17235431L;
    private String dbUrl;
    private String dbUser;
    private String dbPassword;
    
    /**
     * 构造函数
     * @param appKey="hzi45cGZNN6"应用Key
     * @param appSecret"B65NHfcnEv" 应用密钥
     * @param masterKey 产品MasterKey
     * @param productId 产品ID
     * @param dbUrl SQL Server数据库连接URL
     * @param dbUser 数据库用户名
     * @param dbPassword 数据库密码
     */


    public DeviceCrudService(String appKey, String appSecret, String masterKey, long productId,
                             String dbUrl, String dbUser, String dbPassword) {
        this.client = AepDeviceManagementClient.newClient().appKey(appKey).appSecret(appSecret).build();
        this.masterKey = masterKey;
        this.productId = productId;
        this.dbUrl = dbUrl;
        this.dbUser = dbUser;
        this.dbPassword = dbPassword;
        

    }


    /**
     * 创建设备
     * @param deviceName 设备名称
     * @param deviceSn 设备编号（MQTT,T_Link,TCP,HTTP,JT/T808协议必填）
     * @param imei IMEI号（LWM2M,NB网关协议必填）
     * @param operator 操作者
     * @param otherParams 其他参数（JSON格式）
     * @return 创建的设备ID
     * @throws Exception 如果创建失败
     */
    public JSONObject createDevice(String deviceName, String deviceSn, String imei, String operator, JSONObject otherParams) throws Exception {
        CreateDeviceRequest request = new CreateDeviceRequest();

        
        // 构建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("deviceName", deviceName);
        requestBody.put("operator", operator);
        //System.out.println("productId"+productId);
        requestBody.put("productId", 17235431L);

        // 根据协议类型设置不同参数
        if (deviceSn != null && !deviceSn.isEmpty()) {
            requestBody.put("deviceSn", deviceSn);
        }
        
        if (imei != null && !imei.isEmpty()) {
            requestBody.put("imei", imei);
        }
        
        // 添加其他参数
        if (otherParams != null) {
            requestBody.put("other", otherParams);
        }
        byte[] bodyBytes = requestBody.toString().getBytes(StandardCharsets.UTF_8);
        request.setBody(bodyBytes);

        request.setParamMasterKey(masterKey);


        System.out.println("请求体：@@@@@@@@"+requestBody);

        // 调用API创建设备
        CreateDeviceResponse response = client.CreateDevice(request);
        byte[] bodyByte = response.getBody(); // 获取字节数组
        String responseBody = new String(bodyByte, StandardCharsets.UTF_8);
        // 解析响应

        System.out.println("####返回报文；"+responseBody);
        JSONObject jsonResponse = new JSONObject(responseBody);
        
        if (jsonResponse.getInt("code") != 0) {
            throw new Exception("创建设备失败: " + jsonResponse.getString("msg"));
        }
        
        JSONObject result = jsonResponse.getJSONObject("result");
        //String deviceId = result.getString("deviceId");

        
        return result;
    }

    

    /**
     * 更新设备
     * @param deviceId 设备ID
     * @param deviceName 设备名称
     * @param operator 操作者
     * @param otherParams 其他参数（JSON格式）
     * @return 是否更新成功
     * @throws Exception 如果更新失败
     */
    public boolean updateDevice(String deviceId, String deviceName, String operator, JSONObject otherParams) throws Exception {
        UpdateDeviceRequest request = new UpdateDeviceRequest();

        request.setParamDeviceId(deviceId);
        
        // 构建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("deviceName", deviceName);
        requestBody.put("operator", operator);
        requestBody.put("productId", productId);
        
        // 添加其他参数
        if (otherParams != null) {
            requestBody.put("other", otherParams);
        }
        byte[] bodyBytes = requestBody.toString().getBytes(StandardCharsets.UTF_8);
        request.setBody(bodyBytes);
        
        // 调用API更新设备
        UpdateDeviceResponse response = client.UpdateDevice(request);
        byte[] bodyByte = response.getBody(); // 获取字节数组
        String responseBody = new String(bodyByte, StandardCharsets.UTF_8);
        
        // 解析响应
        JSONObject jsonResponse = new JSONObject(responseBody);
        
        if (jsonResponse.getInt("code") != 0) {
            throw new Exception("更新设备失败: " + jsonResponse.getString("msg"));
        }

        request.setParamMasterKey(masterKey);
        return true;
    }
    
    /**
     * 删除设备
     * @param deviceId 设备ID
     * @return 是否删除成功
     * @throws Exception 如果删除失败
     */
    public boolean deleteDevice(String deviceId) throws Exception {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setParamProductId(productId);
        request.setParamDeviceIds(deviceId);
        
        // 调用API删除设备
        DeleteDeviceResponse response = client.DeleteDevice(request);
        byte[] bodyByte = response.getBody(); // 获取字节数组
        String responseBody = new String(bodyByte, StandardCharsets.UTF_8);
        
        // 解析响应
        JSONObject jsonResponse = new JSONObject(responseBody);
        
        if (jsonResponse.getInt("code") != 0) {
            throw new Exception("删除设备失败: " + jsonResponse.getString("msg"));
        }

        request.setParamMasterKey(masterKey);
        return true;
    }

    
    /**
     * 关闭客户端
     */
    public void shutdown() {
        if (client != null) {
            client.shutdown();
        }
    }
}
